package com.atguigu.eduservice.handler.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.common.exception.GuliException;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService subjectService;
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectExcelListener() {
    }

    //从excel一行一行进行读取
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        //excelSubjectData就是每次读取excel内容
        if(excelSubjectData == null) {
            throw new GuliException(20001,"读取失败");
        }

        //添加一级分类
        String oneSubjectName = excelSubjectData.getOneSubjectName();
        //判断表是否存在相同的一级分类
        EduSubject eduSubjectOneExist = this.existOneSubject(oneSubjectName, subjectService);
        if(eduSubjectOneExist == null) {//表不存在相同名称一级分类，进行添加
            eduSubjectOneExist = new EduSubject();
            eduSubjectOneExist.setTitle(oneSubjectName);
            eduSubjectOneExist.setParentId("0");
            subjectService.save(eduSubjectOneExist);
        }

        //添加二级分类
        //获取二级分类
        String twoSubjectName = excelSubjectData.getTwoSubjectName();

        //一级分类id值
        String pid = eduSubjectOneExist.getId();

        EduSubject eduSubjectTwoExist = this.existTwoSubject(twoSubjectName, pid, subjectService);
        if(eduSubjectTwoExist == null) {//表不存在相同名称二级分类，进行添加
            eduSubjectTwoExist = new EduSubject();
            eduSubjectTwoExist.setTitle(twoSubjectName); //二级分类名称
            eduSubjectTwoExist.setParentId(pid);
            subjectService.save(eduSubjectTwoExist);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断二级分类是否存在
    private EduSubject existTwoSubject(String name,String pid,EduSubjectService subjectService) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject edu = subjectService.getOne(wrapper);
        return edu;
    }

    //判断一级分类是否存在
    private EduSubject existOneSubject(String name,EduSubjectService subjectService) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject edu = subjectService.getOne(wrapper);
        return edu;
    }
}
